package com.hcinfos.gsoo.ui;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.overlay.DrivingRouteOverlay;
import com.amap.api.maps2d.overlay.WalkRouteOverlay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkPath;
import com.amap.api.services.route.RouteSearch.DriveRouteQuery;
import com.amap.api.services.route.RouteSearch.OnRouteSearchListener;
import com.amap.api.services.route.RouteSearch.WalkRouteQuery;
import com.amap.api.services.route.WalkRouteResult;
import com.baidu.navisdk.BaiduNaviManager;
import com.baidu.navisdk.BNaviEngineManager.NaviEngineInitListener;
import com.baidu.navisdk.BaiduNaviManager.OnStartNavigationListener;
import com.baidu.navisdk.comapi.routeplan.RoutePlanParams.NE_RoutePlan_Mode;
import com.baidu.navisdk.util.verify.BNKeyVerifyListener;
import com.hcinfos.gsoo.GsooApplication;
import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.util.DialogUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;

public class RouteActivity extends Activity implements OnClickListener,
		OnRouteSearchListener {

	private TextView reg_tv;
	private ImageButton left_ib;
	private TextView center_tv;

	private GsooApplication app;
	private String cityName;
	private SharePreferenceUtil util;

	private MapView mapView;
	private RouteSearch routeSearch;

	private AMap aMap;
	private TextView second_tv;

	// baidu key
	private final static String ACCESS_KEY = "29E5B7Fd813e14a80e6c63b174d6135a";
	private boolean mIsEngineInitSuccess = false;
	private Dialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		app = (GsooApplication) getApplication();
		util = new SharePreferenceUtil(this, "setting");
		cityName = util.loadStringSharedPreference("cityName");
		setContentView(R.layout.activity_route);
		mapView = (MapView) findViewById(R.id.map);
		mapView.onCreate(savedInstanceState);// 此方法必须重写
		initRes();
		// 初始化导航引擎
		BaiduNaviManager.getInstance().initEngine(this, getSdcardDir(),
				mNaviEngineInitListener, ACCESS_KEY, mKeyVerifyListener);
	}

	private String getSdcardDir() {
		if (Environment.getExternalStorageState().equalsIgnoreCase(
				Environment.MEDIA_MOUNTED)) {
			return Environment.getExternalStorageDirectory().toString();
		}
		return null;
	}

	private NaviEngineInitListener mNaviEngineInitListener = new NaviEngineInitListener() {
		public void engineInitSuccess() {
			mIsEngineInitSuccess = true;
		}

		public void engineInitStart() {
		}

		public void engineInitFail() {
		}
	};

	private BNKeyVerifyListener mKeyVerifyListener = new BNKeyVerifyListener() {

		@Override
		public void onVerifySucc() {
		}

		@Override
		public void onVerifyFailed(int arg0, String arg1) {
			Toast.makeText(RouteActivity.this, "key校验失败", Toast.LENGTH_LONG)
					.show();
		}
	};

	private LatLonPoint startPoing;
	private LatLonPoint endPoint;

	private void initRes() {
		dialog = DialogUtil.createProgressDialog(this, "提示", "正在查询线路中...");
		if (aMap == null) {
			aMap = mapView.getMap();
			// registerListener();
		}
		left_ib = (ImageButton) findViewById(R.id.left_ib);
		left_ib.setOnClickListener(this);
		reg_tv = (TextView) findViewById(R.id.reg_tv);
		reg_tv.setOnClickListener(this);
		reg_tv.setText("步行");
		center_tv = (TextView) findViewById(R.id.center_tv);
		center_tv.setText("线路规划");
		second_tv = (TextView) findViewById(R.id.second_tv);
		second_tv.setVisibility(View.VISIBLE);
		second_tv.setText("导  航");
		second_tv.setOnClickListener(this);

		routeSearch = new RouteSearch(this);
		routeSearch.setRouteSearchListener(this);
		startPoing = new LatLonPoint(GsooApplication.lat, GsooApplication.lng);
		String lat = getIntent().getStringExtra("lat");
		String lng = getIntent().getStringExtra("lng");
		if (lat != null) {
			endPoint = new LatLonPoint(Double.parseDouble(lat),
					Double.parseDouble(lng));
			if (dialog != null)
				dialog.show();
			searchRouteResult(startPoing, endPoint, 2);
		} else {
			return;
		}
		// reg_tv.setText("导航");
	}

	@Override
	protected void onPause() {
		super.onPause();
		mapView.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		mapView.onResume();

	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mapView.onSaveInstanceState(outState);
	}

	/**
	 * 方法必须重写
	 */
	public void onDestroy() {
		super.onDestroy();
		mapView.onDestroy();
	}

	private int type = 2;

	private void searchRouteResult(LatLonPoint startPoint,
			LatLonPoint endPoint, int type) {
		final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
				startPoint, endPoint);
		if (type == 2) {// 乘车
			DriveRouteQuery query = new DriveRouteQuery(fromAndTo,
					RouteSearch.DrivingDefault, null, null, "");// 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
			routeSearch.calculateDriveRouteAsyn(query);// 异步路径规划驾车模式查询
		} else {
			WalkRouteQuery query = new WalkRouteQuery(fromAndTo,
					RouteSearch.WalkDefault);
			routeSearch.calculateWalkRouteAsyn(query);// 异步路径规划步行模式查询
		}

	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.left_ib:
			finish();
			break;
		case R.id.reg_tv:

			if (type == 2) {
				type = 3;
				reg_tv.setText("步行");
			} else {
				type = 2;
				reg_tv.setText("驾车");
			}
			searchRouteResult(startPoing, endPoint, type);
			break;
		case R.id.second_tv:
			launchNavigator(startPoing.getLatitude(),
					startPoing.getLongitude(), endPoint.getLatitude(),
					endPoint.getLongitude());
			break;
		}

	}

	/**
	 * 启动GPS导航. 前置条件：导航引擎初始化成功
	 */
	private void launchNavigator(double startLat, double startLng,
			double endLat, double endLng) {
		// 这里给出一个起终点示例，实际应用中可以通过POI检索、外部POI来源等方式获取起终点坐标
		BaiduNaviManager.getInstance().launchNavigator(this, startLat,
				startLng, "", endLat, endLng, "",
				NE_RoutePlan_Mode.ROUTE_PLAN_MOD_MIN_TIME, // 算路方式
				true, // 真实导航
				BaiduNaviManager.STRATEGY_FORCE_ONLINE_PRIORITY, // 在离线策略
				new OnStartNavigationListener() { // 跳转监听

					@Override
					public void onJumpToNavigator(Bundle configParams) {
						Intent intent = new Intent(RouteActivity.this,
								BNavigatorActivity.class);
						intent.putExtras(configParams);
						startActivity(intent);
					}

					@Override
					public void onJumpToDownloader() {
					}
				});
	}

	@Override
	public void onBusRouteSearched(BusRouteResult arg0, int arg1) {

	}

	private DriveRouteResult driveRouteResult;

	@Override
	public void onDriveRouteSearched(DriveRouteResult result, int rCode) {
		if (dialog != null)
			dialog.dismiss();
		if (rCode == 0) {
			if (result != null && result.getPaths() != null
					&& result.getPaths().size() > 0) {
				driveRouteResult = result;
				DrivePath drivePath = driveRouteResult.getPaths().get(0);
				aMap.clear();// 清理地图上的所有覆盖物
				DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(
						this, aMap, drivePath, driveRouteResult.getStartPos(),
						driveRouteResult.getTargetPos());
				drivingRouteOverlay.removeFromMap();
				drivingRouteOverlay.addToMap();
				drivingRouteOverlay.zoomToSpan();
			} else {
				Toast.makeText(RouteActivity.this, "没有线路", 500).show();
			}
		} else if (rCode == 27) {
			Toast.makeText(RouteActivity.this, "网络错误", 500).show();
		} else {
			Toast.makeText(RouteActivity.this, "未知错误" + rCode, 500).show();
		}
	}

	private WalkRouteResult walkRouteResult;

	@Override
	public void onWalkRouteSearched(WalkRouteResult result, int rCode) {
		if (dialog != null)
			dialog.dismiss();
		if (rCode == 0) {
			if (result != null && result.getPaths() != null
					&& result.getPaths().size() > 0) {
				walkRouteResult = result;
				WalkPath walkPath = walkRouteResult.getPaths().get(0);
				aMap.clear();// 清理地图上的所有覆盖物
				WalkRouteOverlay walkRouteOverlay = new WalkRouteOverlay(this,
						aMap, walkPath, walkRouteResult.getStartPos(),
						walkRouteResult.getTargetPos());
				walkRouteOverlay.removeFromMap();
				walkRouteOverlay.addToMap();
				walkRouteOverlay.zoomToSpan();
			} else {
				Toast.makeText(RouteActivity.this, "没有线路", 500).show();
			}
		} else if (rCode == 27) {
			Toast.makeText(RouteActivity.this, "网络错误", 500).show();
		} else {
			Toast.makeText(RouteActivity.this, "未知错误" + rCode, 500).show();
		}
	}

}
